<template>
  <view class="page">
    <view class="address " @tap="goSelectAddress">
      <view class="address__top" v-if="addressOption.province">
        <view class="address__top--sign" style="font-size:11px">收货地址</view>
        <view>{{addressOption.province}} {{addressOption.county}} {{addressOption.city}}</view>
      </view>
      <view class="address__sec ">
        <view style="font-weight:bold">
          <view v-if="addressOption.province">{{addressOption.detailInfo}}</view>
          <view v-else>请选择收货地址</view>
        </view>
        <u-icon name="arrow-right" class="arrow"></u-icon>
      </view>
      <view class="address__user" v-if="addressOption.province">
        <view>{{addressOption.userName}}</view>
        <view style="margin-left:20rpx">{{addressOption.showPhone}}</view>
      </view>
      <image src="https://medusa-small-file.oss-cn-hangzhou.aliyuncs.com/%E5%9B%BE%E6%A0%87/static/xian-fd12ebbd3d.png">
      </image>
    </view>
    <view class="card">
      <view class="card__good">
        <image :src="goodDetail.pic"></image>
        <view class="card__good--detail">
          <view style="font-weight:bold">{{goodDetail.integralGoodName}}</view>
          <view class="card__good--detail--sec" style="margin-top:40rpx">
            <view>数量 X 1</view>
            <view class="price">{{goodDetail.integralPrice}} 积分</view>
          </view>
        </view>
      </view>
    </view>
    <view class="priceCard">
      <view class="priceCard__freight" style="padding-top:20px">
        <view>运费</view>
        <view v-if="!offerOptions.freeShipping">￥{{logistFee}}</view>
        <view v-else>会员免运费</view>
      </view>
      <view class="priceCard__all ">
        合计：
        <view class="priceCard__all--price">{{goodDetail.integralPrice}}积分(+￥{{logistFee}})</view>
      </view>
    </view>
    <view class="form">
      买家留言：
      <textarea class="form-textare" placeholder="对本次交易说明（45字内）" maxlength="45" @input="handleIptChange"></textarea>
    </view>
    <view class="payWay">
      <view v-for="(item, index) in payList" :key="index" class="payWay__balance">
        <view style="display:flex">
          <m-icon name="icontijiaodingdan-yue" color="#FF9C01" v-if="item.id===100"></m-icon>
          <m-icon name="icontijiaodingdan-weixin" color="#6BCC03" v-if="item.id===101"></m-icon>
          <view style="margin-left:10px">{{item.pay}}</view>
        </view>
        <view style="margin-right:20rpx">
          <view v-if="item.id===100">
            <view v-if="!canPayBayAccount">
              <view
                style="width:17px;height:17px;border-radius:50px;background-color:#F5F7FA; border: 1px solid #E8EAF0">
              </view>
            </view>
            <view v-else @tap="choosePayWay" :data-info="item">
              <m-icon name="iconweigouxuan" v-if="!item.chooseFlag" color="#FB485D"></m-icon>
              <m-icon name="icongouxuan" color="#FB485D" v-else></m-icon>
            </view>
          </view>
          <view v-if="item.id===101" @tap="choosePayWay" :data-info="item">
            <m-icon name="iconweigouxuan" v-if="!item.chooseFlag" color="#FB485D"></m-icon>
            <m-icon name="icongouxuan" color="#FB485D" v-else></m-icon>
          </view>
        </view>
      </view>
    </view>
    <view class="submit">
      <view class=" submit__left" style="height:45px">
        <view>总计:</view>
        <view class="submit__left--all">{{goodDetail.integralPrice}}积分(+￥{{logistFee}})</view>
      </view>
      <form @submit="handleSubmit" report-submit="true">
        <button form-type="submit">提交订单</button>
      </form>
    </view>
  </view>
</template>

<script lang='ts'>
  import {
    Component,
    Vue
  } from 'vue-property-decorator'
  import {
    getPrizeOrder,
    payOrder,
    payOrderCallBack,
    getAllAddress,
    getLogistFee,
  } from "@/api/modules/integral";
  import {
    placeAround,
    getadCodBycityCode
  } from "@/api/modules/shipping";
  import {
    getAddressList
  } from "@/api/modules/address";
  import {
    userMsgGet
  } from "@/api/modules/user";
  @Component({})
  export default class IntegralSubmit extends Vue {

    columns: ["余额支付", "微信支付"]
    deliveryShow: boolean = false // 支付方式弹窗
    couponShow: boolean = false // 优惠券弹窗
    goodDetail: any = {
      goodName: "A级红石榴",
      goodSec: "新鲜可口 美味诱人",
      num: 1,
      code: 6000,
      payFee: 10,
    }
    /** 备注信息 */
    buyersNote: string = ""
    addressOption: any = {}
    /** 所选地址编码 */
    region: string = ""
    /** 邮费 */
    logistFee: number = 0
    /** 是否发货返回内 */
    inAround: boolean = true
    address: any = {}
    payList: Array < any > = [{
        pay: "余额支付",
        hasType: true,
        chooseFlag: false,
        id: 100
      },
      {
        pay: "微信支付",
        hasType: true,
        chooseFlag: true,
        id: 101
      },
    ]
    haSubscribed: boolean = false
    payId: number = 101

    /** 是否可以余额支付 */
    canPayBayAccount: boolean = true

    canClick: boolean = false
    // 页面周期函数--监听页面加载
    onLoad(options) {
      if (options.goodDetail) {
        uni.clearStorage();
        uni.setStorage({
          key: "submitData",
          data: options.goodDetail,
        });
        this.getSubmitDetail(options.goodDetail);
      } else {
        uni.getStorage({
          key: "submitData",
          success: res => {
            this.setData({
              address: JSON.parse(options.address),
            });
            this.getSubmitDetail(res.data);
          },
        });
      }
    }
    // 页面周期函数--监听页面显示(not-nvue)
    onShow() {
      const pages = getCurrentPages(); // eslint-disable-line
      const currPage = pages[pages.length - 1];
      if (currPage.$vm.address.id) {
        currPage.$vm.address.showPhone = currPage.$vm.address.phone.replace(
          /(\d{3})\d{4}(\d{4})/,
          "$1****$2",
        );
        this.setData({
          addressOption: currPage.$vm.address,
        });
        this.getAddressCode();
      }
    }

    getSubmitDetail(goodDetail) {
      this.setData({
        goodDetail: JSON.parse(goodDetail),
      });
      this.getUserAdd();
    }

    /**
     * 获取用户默认地址
     */
    getUserAdd() {
      let addressOption = this.addressOption;
      const address = this.address;
      getAddressList({
          type: 1
        })
        .then(res => {
          if (res.length > 0) {
            res.forEach(item => {
              if (item.isDefault === 1) {
                addressOption = item;
                addressOption.showPhone = addressOption.phone.replace(
                  /(\d{3})\d{4}(\d{4})/,
                  "$1****$2",
                );
              }
            });
          }
          this.setData({
            addressOption: address.id ? address : addressOption,
          });
        })
        .then(() => {
          this.getAddressCode();
        })
        .catch(() => {
          uni.showToast({
            title: "获取地址邮编失败",
            icon: "none"
          });
        });
    }

    /**
     * 获取用户选择地址编码
     */
    getAddressCode() {
      const addressOption = this.addressOption;
      getAllAddress({})
        .then(res => {
          res.miniAccountAddress.forEach(item => {
            if (item.id === addressOption.id) {
              this.setData({
                region: item.postCode,
              });
            }
          });
        })
        .then(() => {
          this.getCodeFee();
        })
        .catch(() => {
          uni.showToast({
            title: "获取运费失败",
            icon: "none"
          });
        });
    }

    /**
     * 获取所选地址运费
     */
    getCodeFee() {
      const param = {
        freightTemplateId: this.goodDetail.freightTemplateId,
        regionCode: this.region,
        weight: this.goodDetail.weight,
      };
      getLogistFee(param)
        .then(async res => {
          if (res === -1) {
            uni.showToast({
              title: "选择地址不支持发货",
              icon: "none"
            });
          }
          const userInfo = await userMsgGet({
            infoLevel: 2
          });
          const userMemberInfo = userInfo.infoExtends.memberInfo[0];
          const supplyBonus = userMemberInfo.supplyBonus;
          this.setData({
            logistFee: res <= 0 ? 0.01 : res,
            inAround: res < 0 ? false : true,
            canPayBayAccount: Number(supplyBonus) < Number(res <= 0 ? 0.01 : res) ? false : true,
          });
        })
        .catch(() => {
          uni.showToast({
            title: "选择地址不支持发货",
            icon: "none"
          });
          this.setData({
            inAround: true,
          });
        });
    }

    /** 前往选择地址 */
    goSelectAddress() {
      uni.navigateTo({
        url: `/subcontract/pages/address/address?redirect=submit`,
      });
    }

    /**
     * 选择支付方式
     * @param
     */
    chooseDeliveryMethod() {
      this.setData({
        deliveryShow: true
      });
    }

    /**
     * 选择支付方式
     */
    choosePayWay({
      currentTarget: {
        dataset: {
          info
        },
      },
    }) {
      let payId = 101;
      this.payList.forEach(item => {
        item.chooseFlag = false;
        if (info.pay === item.pay) {
          item.chooseFlag = true;
          payId = item.id;
        }
      });

      this.setData({
        payList: this.payList,
        payId,
      });
    }

    /**
     * 买家备注信息
     */
    handleIptChange(e) {
      const {
        value
      } = e.detail;
      this.buyersNote = value;
    }

    /**
     * 提交订单
     */
    async handleSubmit() {
      await this.$store.dispatch('message/subscribe', [this.$store.state.message.type.sendMsg])

      this.setData({
        haSubscribed: true
      });
      const addressOption = this.addressOption;
      if (!addressOption.detailInfo) {
        uni.showToast({
          title: "请先选择收货地址",
          icon: "none"
        });
        return;
      }
      if (!this.inAround) {
        uni.showToast({
          title: "选择地址不支持发货",
          icon: "none"
        });
        return;
      }
      uni.showLoading({
        mask:true,
        title:"支付中..."
      })
      const deliveryTemplateId = await this.$store.dispatch('message/getTemplateId', this.$store.state.message.type
        .sendMsg);
      const location = addressOption.location.split(",");
      const addressDetail = await placeAround(`${location[0]},${location[1]}`);
      const poi = addressDetail.pois[0];
      const cityCode = await getadCodBycityCode(poi.citycode);
      const {
        pcode,
        adcode
      } = poi;
      const param = {
        provinceCode: pcode,
        cityCode: cityCode,
        areaCode: adcode,
        address: `${addressOption.province} ${addressOption.city} ${addressOption.county} ${addressOption.detailInfo}`,
        orderType: false,
        payType: this.payId,
        price: this.goodDetail.integralPrice,
        prizeId: this.goodDetail.id,
        integralGoodsPic: this.goodDetail.pic,
        receiverName: addressOption.userName,
        shippingFee: this.logistFee,
        telPhone: addressOption.phone,
        buyersNote: this.buyersNote,
        deliveryTemplateId: this.haSubscribed ? deliveryTemplateId : -1,
      };

      if (this.payId === 100) {
        this.getByAccount(param);
        return;
      }
      getPrizeOrder(param)
        .then(res => {
          const prizeOrderId = res;
          payOrder(res, {})
            .then(v => {
              const wxResult = v.wxResult;
              const payParam = {
                timeStamp: wxResult.timeStamp,
                nonceStr: wxResult.nonceStr,
                package: wxResult.packageValue,
                signType: wxResult.signType,
                paySign: wxResult.paySign,
                success: () => {
                  payOrderCallBack({
                    isSucceed: true,
                    prizeOrderId
                  });
                  this.$Popup.modal({
                    title:"支付成功",
                    content:"您已成功支付，可联系商家查看物流信息"
                  }).then(() => {
                    const pages = getCurrentPages(); // eslint-disable-line
                    const prevPage = pages[pages.length - 2];
                    prevPage.$vm.setData({
                      // 将要传递的参数在这里直接setData。上个页面就会执行这里的操作。
                      id: this.goodDetail.id,
                    });
                    setTimeout(() => {
                      uni.navigateBack({
                        delta: 1,
                      });
                    }, 1000);
                  }).catch(()=>{
                    this.$Popup.toast("支付失败")
                  });
                },
                fail: () => {
                  this.$Popup.toast("支付失败")
                  payOrderCallBack({
                    isSucceed: false,
                    prizeOrderId,
                  });
                },
              };
              uni.requestPayment(payParam);
            })
            .catch(() => {
              payOrderCallBack({
                isSucceed: false,
                prizeOrderId,
              });
            });
        })
        .catch(err => {
          this.$Popup.toast(err || "支付失败")
        });
    }

    /**
     * 余额支付
     */
    getByAccount(param) {
      if (this.canClick) {
        return;
      }
      getPrizeOrder(param)
        .then(res => {
          this.canClick = true;
          this.$Popup.modal({
            title:"支付成功",
            content:"您已成功支付，可联系商家查看物流信息"
          }).then(() => {
            payOrderCallBack({
              isSucceed: true,
              prizeOrderId: res
            }).then(() => {
              this.canClick = false;
              const pages = getCurrentPages(); // eslint-disable-line
              const prevPage = pages[pages.length - 2];
              prevPage.$vm.setData({
                // 将要传递的参数在这里直接setData。上个页面就会执行这里的操作。
                id: this.goodDetail.id,
              });
              setTimeout(() => {
                uni.navigateBack({
                  delta: 1,
                });
              }, 1000);
            });
          }).catch(()=>{
            this.$Popup.toast("支付失败")
          });
        })
        .catch(err => {
          uni.showToast({
            title: `${err}`,
            icon: "none"
          });
        });
    }
  }
</script>

<style lang="scss" scoped>
  @import "@/assets/styles/submit/submit.scss";
  .page{
    padding-bottom: calc(90rpx + constant(safe-area-inset-bottom));
    padding-bottom: calc(90rpx + env(safe-area-inset-bottom));
  }

  .payWay__balance {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 50px;
  }

  .submit {
    display: -webkit-box;
    display: flex;
    -webkit-box-orient: horizontal;
    -webkit-box-direction: normal;
    flex-direction: row;
    -webkit-box-align: center;
    align-items: center;
    height: 90rpx;
    position: fixed;
    bottom: 0;
    padding-left: 20px;
    width: 750rpx;
    border-top: 1rpx solid #e9e9e9;
    background-color: white;
    display: flex;
    -webkit-box-pack: end;
    justify-content: space-between;
    -webkit-box-align: end;
    align-items: flex-end;

  }

  .submit__left--all {
    display: -webkit-box;
    display: flex;
    -webkit-box-align: end;
    align-items: flex-end;
    color: #fa5555;
    margin-left: 10px;
  }
</style>